package com.cyy.chat.model;

import com.cyy.chat.model.parama.ChatGptApiParam;
import com.cyy.chat.model.result.ChatGptApiResult;
import com.cyy.chat.model.parama.Message;
import com.google.gson.Gson;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

@Component
public class ChatGptModel {
    private final Message systemMsg = new Message("system",
            "Use the text provided to form your answer, but avoid copying the text verbatim and avoid mentioning that you referenced the text in your answer. " +
                    "Try to use your own words when possible. Keep your answer under 5 sentences." +
                    "If the question is not relevant to the text provided you just need to reply in Chinese: \"Sorry, I can't provide you with the answer to {question}.\" " +
                    "If not ask please chat normally." +
                    "Be accurate, helpful, concise, and clear.");
    @Autowired
    private OkHttpClient openAiHttpClient;
    private final ChatGptApiParam chatGptApiParam = new ChatGptApiParam();

    public String doChatDeepseek(String apiKey, String question, List<String> passages) {
        StringBuilder builder = new StringBuilder();
        for (int i = 1; i <= passages.size(); i++) {
            builder.append(i).append(".").append(passages.get(i - 1)).append("\n");
        }

        List<Message> messageList = new ArrayList<>();
        messageList.add(this.systemMsg);
        String msg = "请根据以下文本回答问题：\n{%s}\n\n参考文本：\n{%s}";
        String formattedMsg = String.format(msg, question, builder.toString());
        messageList.add(new Message("user", formattedMsg));

        this.chatGptApiParam.setMessages(messageList);
        this.chatGptApiParam.setModel("deepseek-chat"); // 正确模型名

        Gson gson = new Gson();
        String json = gson.toJson(this.chatGptApiParam);

        RequestBody body = RequestBody.create(json, MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder()
                .url("https://api.deepseek.com/v1/chat/completions")
                .addHeader("Authorization", apiKey) // 添加 Bearer 前缀
                .addHeader("Content-Type", "application/json") // 显式指定 Content-Type
                .post(body)
                .build();

        try (Response response = this.openAiHttpClient.newCall(request).execute()) {
            if (response.code() == 200) {
                ChatGptApiResult result = gson.fromJson(response.body().string(), ChatGptApiResult.class);
                return result.getChoices().get(0).getMessage().getContent();
            } else if (response.code() == 402) {
                return "错误：账户余额不足（402）";
            } else {
                return "DeepSeek 接口错误，状态码: " + response.code() + ", 响应: " + response.body().string();
            }
        } catch (Exception e) {
            return "请求异常: " + e.getMessage();
        }
    }


}
